package com.huayu.threadpools.lession2;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestLatch {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(10);
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Long start = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            executorService.submit(new Check(countDownLatch));
        }
        executorService.shutdown();
        countDownLatch.await();
        System.out.println("所有任务执行完毕！耗时："+(System.currentTimeMillis()-start)/1000);

    }

    static class Check implements Runnable{

        private CountDownLatch countDownLatch;

        public Check(CountDownLatch countDownLatch) {
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(new Random().nextInt(10)*1000);
                System.out.println(Thread.currentThread().getName()+"，完成任务。。。");
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
